package edu.neu.swc.cloud.controller;

import com.alibaba.fastjson.JSON;
import edu.neu.swc.cloud.domain.EquipCata;
import edu.neu.swc.cloud.domain.Equipment;
import edu.neu.swc.cloud.domain.QueryInfo;
import edu.neu.swc.cloud.domain.Rent;
import edu.neu.swc.cloud.service.CategoryService;
import edu.neu.swc.cloud.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("equip")
public class EquipmentController {

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    CategoryService categoryService;

    @RequestMapping("/equipList")
    public String equipList(QueryInfo queryInfo){
        int numbers = equipmentService.getEquipCounts("%" + queryInfo.getQuery() + "%");
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<Equipment> equipmentList = equipmentService.findEquipByQuery("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",equipmentList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/allEquipTypeList")
    public String allEquipTypeList(){
        List<EquipCata> equipCataList = categoryService.findAllEqu();
        Map<String,Object> res = new HashMap<>();
        res.put("data",equipCataList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/addEquip")
    public String addEquip(@RequestBody Equipment equipment){
        equipmentService.addEquip(equipment);
        return "success";
    }

    @RequestMapping("/getUpdate")
    public String getUpdate(int id){
        Equipment equip = equipmentService.findEquipById(id);
        return JSON.toJSONString(equip);
    }

    @RequestMapping("/editEquip")
    public String editEquip(@RequestBody Equipment equipment){
        equipmentService.update(equipment);
        return "success";
    }

    @RequestMapping("/deleteEquip")
    public String deleteEquip(int id){
        Equipment equipment = equipmentService.findEquipById(id);
        if(equipment.getEq_rent() == 0){
            equipmentService.deleteEquipById(id);
            return "success";
        }
        return "error";
    }

    @RequestMapping("/shutEquip")
    public String shutEquip(int id){
        equipmentService.shutById(id);
        return "success";
    }

    @RequestMapping("/startEquip")
    public String startEquip(int id){
        equipmentService.startById(id);
        return "success";
    }
}
